import {
	PERFIX,
	kfs,
	IM_SDKAppID,
	IM_secretKey,
	HTTP_REQUEST_URL
} from '@/config/app';
import store from '@/store/index.js';
import {
	TUIChatKit,
	genTestUserSig,
} from "../TUIKit";
import TencentCloudChat from '@tencentcloud/chat';
import {
	vueVersion
} from "../TUIKit/adapter-vue";
import {
	TUILogin
} from "@tencentcloud/tui-core";

import TIMPushConfigs from "../timpush-configs.json";

//im客服
// import {
// 	setCustomerServiceAccounts
// } from "../TUIKit/tui-customer-service-plugin";
// setCustomerServiceAccounts(kfs) 
// 设置新的客服号


//im推送
// import timpushConfigs from "./timpush-configs.json"; // IM控制台 > 推送管理 > 接入设置下载配置文件
// IM控制台 > 推送管理 > 接入设置下载配置文件
// const TIMPush = uni.requireNativePlugin("TencentCloud-TIMPush");

let chat = TencentCloudChat.create({
	SDKAppID: IM_SDKAppID // Replace `0` with the `SDKAppID` of your Chat app during access.
});
chat.setLogLevel(4);
store.commit('setImChat', chat)
// chat.registerPlugin({
// 	'tim-push': TIMPush,
// 	pushConfig: {
// 		androidConfig: timpushConfigs, // Android 推送配置，如不需要可传空。
// 		iOSConfig: {
// 			"iOSBusinessID": "41535" // iOS 推送配置，如不需要可传空。
// 		}
// 	}
// })
imEventListen();
export function init() {
	if (uni.getStorageSync('mobile')) {
		// 必填信息
		const config = {
			userID: PERFIX + uni.getStorageSync('mobile'), // User ID
			SDKAppID: IM_SDKAppID, // Your SDKAppID
			secretKey: IM_secretKey, // Your secretKey
		};
		uni.$chat_userID = config.userID;
		uni.$chat_SDKAppID = config.SDKAppID;
		uni.$chat_secretKey = config.secretKey;


		uni.$chat_userSig = genTestUserSig(config).userSig;
		// TUIChatKit 初始化
		TUIChatKit.init();
	}
}


function imEventListen() {
	chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, function(event) {
		console.log("MESSAGE_RECEIVED", event);
		const actionType = JSON.parse(event.data[0].payload.data).actionType;
		const cmd = JSON.parse(JSON.parse(event.data[0].payload.data).data).data.cmd;
		const call_end = JSON.parse(JSON.parse(event.data[0].payload.data).data).call_end;
		console.log("actionType===============", actionType)
		switch (actionType) {
			case 1:
				if (cmd === 'videoCall' || cmd === 'audioCall') console.log("发起通话");
				if (cmd === 'hangup') console.log("通话已结束,通话时长:" + call_end);

				break;
			case 2:
				console.log("取消通话")
				break;
			case 3:
				console.log("已接听")
				break;
			case 4:
				console.log("拒绝通话")
				break;
			case 5:
				console.log("超时未接听")
				break;
			default:
				break;
		}

		getMsgCount()
		// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
		// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
		// event.data - 存储 Message 对象的数组 - [Message]
	});
	// chat.on(TencentCloudChat.EVENT.SDK_NOT_READY, function(event) {
	// 	console.log("SDK is not ready:", event);
	// });

	// chat.on(TencentCloudChat.EVENT.SDK_READY, function(event) {
	// 	console.log("SDK is ready:", event);
	// });

	// chat.on(TencentCloudChat.EVENT.CONNECTING, function(event) {
	// 	console.log("Connecting to IM server...", event);
	// });

	// chat.on(TencentCloudChat.EVENT.CONNECT_SUCCESS, function(event) {
	// 	console.log("Successfully connected to IM server", event);
	// });

	// chat.on(TencentCloudChat.EVENT.CONNECT_FAILED, function(event) {
	// 	console.log("Failed to connect to IM server", event);
	// });

	chat.on("disconnected", function(event) {
		console.log("Disconnected from IM server===========", event);
		init();
		// Here you can handle manual reconnection if needed
	});
	chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, function(event) {
		uni.setStorageSync("onTotalUnreadMessageCountUpdated", event.data)
		store.commit("getC2cUnreadMsgNum", event.data)

		// #ifdef APP-PLUS
		//是否在登入状态（看自己代码检测登入状态的判断方式）
		if (uni.getStorageSync('mobile')) {
			uni.request({
				url: HTTP_REQUEST_URL + '/tencentIm/getC2cUnreadMsgNum',
				data: {
					mobile: uni.getStorageSync('mobile')
				},
				header: {
					xzdToken: uni.getStorageSync("xzdToken")
				},
				success: (res) => {
					uni.request({
						url: HTTP_REQUEST_URL + '/basic/getNoticeNum',
						data: {
							mobile: uni.getStorageSync('mobile')
						},
						header: {
							xzdToken: uni.getStorageSync("xzdToken")
						},
						success: (r) => {
							var num = Number(r.data.data.other) + Number(r.data.data
								.system) + Number(uni.getStorageSync(
								"onTotalUnreadMessageCountUpdated"))
							console.log(num)
							if (num > 0) {
								plus.runtime.setBadgeNumber(num)
								uni.setTabBarBadge({
									index: 3,
									text: String(num)
								})
							} else {
								uni.removeTabBarBadge({
									index: 3
								})
							}
						}
					})
				}
			})
		}
		// #endif 
		getMsgCount()
	});
	// chat.on(TencentCloudChat.EVENT.SDK_READY, function() {
	// 	console.log("SDK_READY");
	// 	getMsgCount()
	// });
}
// 获取单聊和群聊会话的未读总数
function getMsgCount() {
	let totalUnreadCount = chat.getTotalUnreadMessageCount();
	store.commit('setImMsgCount', totalUnreadCount) //每次累加 5
}
export function login() {

	if (uni.getStorageSync('mobile')) {
		const config = {
			userID: PERFIX + uni.getStorageSync('mobile'), // User ID
			SDKAppID: IM_SDKAppID, // Your SDKAppID
			secretKey: IM_secretKey, // Your secretKey
		};
		uni.$chat_userID = config.userID;
		uni.$chat_SDKAppID = config.SDKAppID;
		uni.$chat_secretKey = config.secretKey;

		uni.$chat_userSig = genTestUserSig(config).userSig;
		// TUIChatKit 初始化
		TUIChatKit.init();

		console.log(uni.$chat_userID)

		//const TIMPush = uni.requireNativePlugin("TencentCloud-TIMPush");
		//console.warn(`TencentCloud-TIMPush: uni.requireNativePlugin ${!!TIMPush ? 'success' : 'fail'}`);
		//uni.$TIMPush = TIMPush;
		//uni.$TIMPushConfigs = TIMPushConfigs || {};

		//if (uni.$TIMPush) {
		//uni.$TIMPush.setOfflinePushListener((data) => {
		// 透传 entity 中的内容，不包含推送的 Message
		//console.log('setOfflinePushListener', data);
		//});
		//}

		// TUICore login
		TUILogin.login({
			SDKAppID: uni.$chat_SDKAppID,
			userID: uni.$chat_userID,
			// UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文。
			// 该方法仅适合本地跑通 Demo 和功能调试，详情请参见 https://cloud.tencent.com/document/product/269/32688     
			userSig: uni.$chat_userSig,
			// 如果您需要发送图片、语音、视频、文件等富媒体消息，请设置为 true
			useUploadPlugin: true,
			// 本地审核可识别、处理不安全、不适宜的内容，为您的产品体验和业务安全保驾护航
			// 此功能为增值服务，请参考：https://cloud.tencent.com/document/product/269/79139
			// 如果您已购买内容审核服务，开启此功能请设置为 true
			useProfanityFilterPlugin: false,
			//TIMPush: uni.$TIMPush, // APP 注册推送插件
			//pushConfig: {
			//androidConfig: uni.$TIMPushConfigs,   // Android 推送配置，如不需要可传空。
			//iOSConfig: {    
			//"iOSBusinessID": "43600" // iOS 推送配置，如不需要可传空。
			//}    
			//},
			framework: `vue${vueVersion}` // 当前开发使用框架 vue2 / vue3
		}).then(() => {
			getMsgCount();

			if ((uni.getStorageSync('mobile')) && (uni.getStorageSync("xzdToken"))) {
				uni.request({
					url: HTTP_REQUEST_URL + '/tencentIm/getC2cUnreadMsgNum',
					data: {
						mobile: uni.getStorageSync('mobile')
					},
					header: {
						xzdToken: uni.getStorageSync("xzdToken")
					},
					success: (res) => {
						uni.request({
							url: HTTP_REQUEST_URL + '/basic/getNoticeNum',
							data: {
								mobile: uni.getStorageSync('mobile')
							},
							header: {
								xzdToken: uni.getStorageSync("xzdToken")
							},
							success: (r) => {
								var num = Number(r.data.data.other) + Number(r.data.data
									.system) + Number(uni.getStorageSync(
									"onTotalUnreadMessageCountUpdated"))
								console.log(num)
								if (num > 0) {

									// #ifdef APP-PLUS
									plus.runtime.setBadgeNumber(num)
									// #endif 

									console.log('设置消息标');

									uni.setTabBarBadge({
										index: 3,
										text: String(num)
									})
								} else {
									uni.removeTabBarBadge({
										index: 3
									})
								}
							}
						})
					}
				})
			}

		});

	}
}

export function logout() {
	let promise = chat.logout();
	promise.then(function(imResponse) {
		console.log("imResponse====", imResponse); // 登出成功
	}).catch(function(imError) {
		console.warn('logout error:', imError);
	});
}